package com.sukaiyi.leetcode._1116print_zero_even_odd;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

/**
 * @author sukaiyi
 * @date 2020/06/24
 */
public class ZeroEvenOdd {

    private final Semaphore zeroSemaphore = new Semaphore(1);
    private final Semaphore evenSemaphore = new Semaphore(0);
    private final Semaphore oddSemaphore = new Semaphore(0);

    private final int n;

    private int current = 1;

    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    public void zero(IntConsumer printNumber) throws InterruptedException {
        while (current <= n) {
            zeroSemaphore.acquire();
            if (current > n) {
                break;
            }
            printNumber.accept(0);
            if (current % 2 == 0) {
                evenSemaphore.release();
            } else {
                oddSemaphore.release();
            }
        }
        evenSemaphore.release();
        oddSemaphore.release();
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while (current <= n) {
            evenSemaphore.acquire();
            if (current > n) {
                break;
            }
            printNumber.accept(current++);
            zeroSemaphore.release();
        }
        zeroSemaphore.release();
        oddSemaphore.release();
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while (current <= n) {
            oddSemaphore.acquire();
            if (current > n) {
                break;
            }
            printNumber.accept(current++);
            zeroSemaphore.release();
        }
        zeroSemaphore.release();
        evenSemaphore.release();
    }
}
